<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: Dean <zxxjjforever@163.com>
// +----------------------------------------------------------------------
namespace api\user\controller;

use cmf\controller\RestUserBaseController;
use think\Db;
use think\Validate;
use api\user\model\MaterialModel as Material;
use api\user\model\TagModel as Tag;
use api\user\model\UserModel as User;
use app\common\logic\Tools;

class MaterialController extends RestUserBaseController
{

    /**
     * [get_material_list 获取素材列表]
     * @param  Material $Material [素材模型类]
     * @return [data]             [素材二位数组]
     */
    public function get_material_list(Material $Material,Tag $Tag){
        $userId       = $this->getUserId();
        $title = trim($this->request->param('title'));
        $address = trim($this->request->param('address'));
        $type = $this->request->param('type');
        $tag = $this->request->param('tag');
        $order = $this->request->param('order')?$this->request->param('order'):1;
        $param = $this->request->param();
        $where = [];
        //标题
        if (!empty($title)) {
           // $where['m.title'] = ['like', "%$title%"];
            $whereOr['m.address|m.title'] = ['like', "%$title%"];
        }else{
            $whereOr=[];
        }
        //标签
        if (!empty($tag)) {

            $where['m.tags'] = ['like', "%$tag%"];
        }

        //类型
        if (!empty($type)) {
        	if($type == -1){
        		$type=0;
        	}
            $where['m.format'] = $type;
        }
       // var_dump(0=='');die;
        //$this->success('',$where);die;
        //排序
        if($order == 1){
            //按创建时间
            $sort = 'm.createTime desc';
        }else{
            //按创建地点首字母
            $sort = 'm.address desc';
        }

         //时间搜索
        $startTime = empty($param['start_time']) ? 0 : strtotime($param['start_time']);
        $endTime   = empty($param['end_time']) ? 0 : strtotime($param['end_time'].'+1 month');
        //var_dump($startTime);
        if (!empty($startTime) && !empty($endTime)) {
            $where['m.createTime'] = [['>= time', $startTime], ['<= time', $endTime]];
        } else {
            if (!empty($startTime)) {
                $where['m.createTime'] = ['>= time', $startTime];
            }
            if (!empty($endTime)) {
                $where['m.createTime'] = ['<= time', $endTime];
            }
        }
        //var_dump($where);die;

        $where['m.userId'] = $userId;
        $where['m.show_status'] = 1;//非隐藏
        $where['m.delete_time'] = null;//非删除
       // var_dump($where);die;
        $data = $Material->getList($where,$whereOr,$sort,$param);
        //$this->success($Material->getLastSql());die;
        foreach ($data as $key => $value) {
            if($value['images'] !=''){
                $data[$key]['imgs'] = explode(',', $value['images']);
                //获取缩略图
                $imgs = [];
                for ($i=0; $i < 4 ; $i++) { 
                    if(!empty($data[$key]['imgs'][$i])){
                        $imgs[] = $data[$key]['imgs'][$i].'-thumbnail300x300';
                        
                    }        
                }
                /*foreach($data[$key]['imgs'] as $k=>$val){
                    if(!empty($val)){
                        $imgs[$k] = $val.'-thumbnail300x300';
                        $rs = Tools::getHttp($val.'-thumbnail300x300');
                        if(strlen($rs) > 30){
                            $imgs[$k] = $val.'-thumbnail300x300';
                        }else{
                            $imgs[$k] = $val;
                        }  
                    }              
                }*/
                $data[$key]['imgs'] = $imgs;
              
            }
            if($value['video'] !=''){
                $data[$key]['videos'] = explode(',', $value['video']);
            }
            if($value['audio'] !=''){
                $data[$key]['audios'] = explode(',', $value['audio']);
            }
            if($value['voice'] !=''){
                $data[$key]['voices'] = explode(',', $value['voice']);
            }
			if(!empty($value['rec_time'])){
                $data[$key]['rec_time'] = explode(',', $value['rec_time']);
            }else{
              $data[$key]['rec_time'] = '';
            }
            //if($value['rec_time'] !=''){
                //$data[$key]['rec_time'] = explode(',', $value['rec_time']);
            //}

            $date = substr($value['createTime'], 0,10);
            $time = substr($value['createTime'], -8);

            $city = mb_substr($value['city'],0, mb_strlen($value['city'])-1);
           // var_dump($date);
            $data[$key]['date'] = explode('-',$date);
            $data[$key]['time'] = explode(':',$time);
            $data[$key]['city'] = $city;
            if($value['city'] !=''){
            	$data[$key]['adr'] = $city." ".$value['address'];
            }else{
            	$data[$key]['adr'] = $value['address'];
            }
            
        }
        $this->success('',$data);
    }


    //获取素材详情
    public function get_material_info(Material $Material){
        $id = $this->request->param('id');
        $data = $Material->getInfo(['id'=>$id]);
        if($data['images'] !=''){
            $data['imgs'] = explode(',', $data['images']);
        }
        if($data['video'] !=''){
            $data['videos'] = explode(',', $data['video']);
        }
         if($data['audio'] !=''){
            $data['audios'] = explode(',', $data['audio']);
        }
        if($data['voice'] !=''){
            $data['voices'] = explode(',', $data['voice']);
        }
         if($data['rec_time'] !=''){
            $data['rec_time'] = explode(',', $data['rec_time']);
        }
        $data['userName'] = Db::name('app_user')->where(['id'=>$data['userId']])->value('realName');
        $this->success('',$data);
    }



    //成长点滴容量
    public function get_memory(Material $Material){
        $userId=$this->getUserId();
       
        $where['userId']=array('eq',$userId);
        $where['memory']=array('neq','');
        $re=$Material->where($where)->sum('memory');
      
        echo round($re/1024/1024,2);exit;
        $this->success('',$re);
    }
    //内存单位换算函数
    // public function setupSize($fileSize) {     
    // $size = sprintf("%u", $fileSize);     
    // if($size == 0) {          
    //     return("0KB");     
    // }    
    // $sizename = array( " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");     
    // return round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizename[$i]; 
    // }


    /**
     * [createInfo 发布素材]
     * @param  Tag    $Tag [标签模型]
     * @param  userId [用户ID]
     * @param  name [标签名称]
     * @return 
     */
    public function createInfo(Material $Material)
    {
        $userId       = $this->getUserId();
        $data = $this->request->post();
        $data['userId'] = $userId;
        if(mb_strlen($data['title']) >250){
            $this->error('标题字数不能超过250字');die;
        }
    
        $data['createTime'] = date('Y-m-d H:i',time());

        if(!empty($data['tags'])){
            $data['tags'] = implode(',', $data['tags']);
        }
        if(!empty($data['images'])){  
            $data['images'] = implode(',', $data['images']);
        }
        if(!empty($data['video'])){
            $data['video'] = implode(',', $data['video']);
        }
        if(!empty($data['audio'])){
            $data['audio'] = implode(',', $data['audio']);
        }
        if(!empty($data['voice'])){
            $data['voice'] = implode(',', $data['voice']);
        }
        if(!empty($data['rec_time'])){
            $data['rec_time'] = implode(',', $data['rec_time']);
        }
      
        $re = $Material->create_data($data);
        if($re){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }


    public function update_material(Material $Material){
        $data = $this->request->post();
        $re = $Material->update_data($data);
        if($re){
            $this->success('保存成功');
        }else{
            $this->error('保存失败');
        }
    }

    /**
     * [del_material 删除素材]
     * @param  Tag    $Tag [标签模型]
     * @param  id [主键id]
     * @return 
     */
    public function del_material(Material $Material)
    {
        $id = $this->request->param('id');
        $re = $Material->destroy($id);
        if($re){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

}
